/** menuTree 数据处理的工具类 **/
export function initData(treeArray, idsArray, openFolder) {
  // console.log("initData treeArray="+treeArray);
  treeArray = initNodeParam(treeArray, openFolder, true, true);

  let treeNodeArray = [];
  let depth = 0;
  /** 数据类型转换 多层treeArray转一层NodeArray **/
  getTreeNodeArray(treeArray, treeNodeArray, depth);
  // console.log(treeNodeArray, height);
  treeNodeArray.sort((a, b) => {
    return b.level - a.level
  });
  let height = treeNodeArray[0].level;
  // console.log(treeNodeArray, height);

  /** Checkbox处理 **/
  /** 设置一层的CheckBox **/
  treeNodeArray = updateTreeNodeCheckBox(height, treeNodeArray, idsArray);
  // console.log(treeNodeArray);
  /** 一层映射多层TreeData **/
  updateTreeCheckBox(treeArray, treeNodeArray);
  // console.log(initTreeData);
  return treeArray;
}

/** 拖拽后重建数据更新checkbox **/
export function rebuildData(treeRootArray, idsArray) {
  // console.log("treeRootArray=="+JSON.stringify(treeRootArray));
  let treeNodeArray = [];
  let depth = 0;
  /** 数据类型转换 多层转一层 **/
  getTreeNodeArray(treeRootArray, treeNodeArray, depth);
  // console.log(treeNodeArray, height);
  treeNodeArray.sort((a, b) => {
    return b.level - a.level
  });
  let height = treeNodeArray[0].level;
  // console.log(treeNodeArray, height);
  /** 根据叶子节点状态重新获取整个树的节点状态 应用于拖拽后 **/
  // console.log("rebuildData idsArray==" + idsArray);
  idsArray = getIdsWithLeafCheckBox(treeNodeArray);
  // console.log("rebuildData idsArray==" + idsArray);
  // console.log("idsArray=="+this.idsArray);
  /** 设置一层的CheckBox **/
  treeNodeArray = updateTreeNodeCheckBox(height, treeNodeArray, idsArray);
  // console.log(treeNodeArray);
  /** 一层映射多层 **/
  updateTreeCheckBox(treeRootArray, treeNodeArray);
  // console.log(JSON.stringify(treeRootArray));
  return {treeRootArray: treeRootArray, idsArray: idsArray};
}

export function updateData(treeRootArray, idsArray, node) {
  // console.log("updateData node==" + JSON.stringify(node));
  // console.log("updateData treeRootArray=="+JSON.stringify(treeRootArray));
  let childArray = [];
  getNodeWithParentId(node.id, treeRootArray, childArray);
  // console.log("updateData child::" + JSON.stringify(childArray));
  let childIdsArray = [];
  getChildIds(childArray, childIdsArray);
  // console.log("updateData childIdsArray::" + JSON.stringify(childIdsArray));
  // console.log("updateData idsArray==" + idsArray);
  idsArray = updateIdsArray(node.id, childIdsArray, idsArray);
  // console.log("updateData idsArray==" + idsArray);
  let treeNodeArray = [];
  let depth = 0;
  /** 数据类型转换 多层转一层 **/
  getTreeNodeArray(treeRootArray, treeNodeArray, depth);
  // console.log(treeNodeArray, height);
  treeNodeArray.sort((a, b) => {
    return b.level - a.level
  });
  let height = treeNodeArray[0].level;
  // console.log(treeNodeArray, height);
  /** 设置一层的CheckBox **/
  treeNodeArray = updateTreeNodeCheckBox(height, treeNodeArray, idsArray);

  // console.log(treeNodeArray);
  /** 一层映射多层 **/
  updateTreeCheckBox(treeRootArray, treeNodeArray);
  return {treeRootArray: treeRootArray, idsArray: idsArray};
}

// 递归 Node数据初始化处理 是否展开显示open 是否显示CheckBox 是否显示Btn
function initNodeParam(arr, openFolder, showCheckBox, addNodeBtn) {
  if (arr && arr.length) {
    for (let i = 0, len = arr.length; i < len; i++) {
      if (arr[i] instanceof Object) {
        if (!arr[i].isCheck) {
          arr[i]['isCheck'] = false;
        }
        if (!arr[i].indeterminate) {
          arr[i]['indeterminate'] = false;
        }
        if (!arr[i].open) {
          arr[i]['open'] = openFolder;
        }
        if (!arr[i].showCheckBox) {
          arr[i]['showCheckBox'] = showCheckBox;
        }
        if (!arr[i].addNodeBtn) {
          arr[i]['addNodeBtn'] = addNodeBtn;
        }
        initNodeParam(arr[i].menuChild, openFolder, showCheckBox, addNodeBtn);
      }
    }
  }
  return arr;
}

/** 单个变量表示checkbox状态 转 双变量表示 用于用图片模拟的checkbox视图更新 **/
function updateTreeCheckBox(treeArray, treeNodeArray) {
  for (let n = 0; n < treeArray.length; n++) {
    if (getCheckBoxStatus(treeArray[n].id, treeNodeArray) === 'unCheck') {
      treeArray[n] = Object.assign({}, treeArray[n], {
        'isCheck': false,
        'indeterminate': false
      });
    }
    if (getCheckBoxStatus(treeArray[n].id, treeNodeArray) === 'indeterminate') {
      treeArray[n] = Object.assign({}, treeArray[n], {
        'isCheck': false,
        'indeterminate': true
      });
    }
    if (getCheckBoxStatus(treeArray[n].id, treeNodeArray) === 'isCheck') {
      treeArray[n] = Object.assign({}, treeArray[n], {
        'isCheck': true,
        'indeterminate': false
      });
    }
    if (treeArray[n].menuChild && treeArray[n].menuChild.length) {
      updateTreeCheckBox(treeArray[n].menuChild, treeNodeArray);
    }
  }
}

function getCheckBoxStatus(id, treeNodeArray) {
  for (let n = 0; n < treeNodeArray.length; n++) {
    if (treeNodeArray[n].id === id) {
      return treeNodeArray[n].checkbox;
    }
  }
}

// 将数据结构多层Tree转为单层obj数组
function getTreeNodeArray(array, treeNodeArray, depth) {
  if (array && array.length) {
    for (let i = 0; i < array.length; i++) {
      let treeNode = {
        id: array[i].id,
        pid: array[i].pid,
        name: array[i].name,
        level: depth,
        checkbox: getCheckBoxStatusWithOBJ(array[i])
      };
      if (array[i].menuChild && array[i].menuChild.length) {
        getTreeNodeArray(array[i].menuChild, treeNodeArray, depth + 1);
      } else {
      }
      treeNodeArray.push(treeNode);
    }
  }
}

function getCheckBoxStatusWithOBJ(obj) {
  if (obj.isCheck === false && obj.indeterminate === false) {
    return 'unCheck';
  }
  if (obj.isCheck === false && obj.indeterminate === true) {
    // return "indeterminate";
    // 拖动后 设置中间节点初始状态为未选中
    return 'unCheck';// 中间节点CheckBoxStatus会在updateTreeCheckBox时由子到父重新赋值
  }
  if (obj.isCheck === true && obj.indeterminate === false) {
    return 'isCheck';
  }
  return 'unCheck';
}

// 根据level反向遍历Tree 设置checkbox
function updateTreeNodeCheckBox(height, treeNodeArray, idsArray) {
  let array = copyArray(treeNodeArray);
  for (let i = height; i >= 0; i--) {
    let heightTreeNodeArray = getTreeNodeWithHeight(i, treeNodeArray);
    for (let n = 0; n < heightTreeNodeArray.length; n++) {
      // 从最深一层循环 比较id
      if (existId(heightTreeNodeArray[n].id, idsArray)) {
        let childTreeNodeArray = getChildTreeNode(heightTreeNodeArray[n].id, array);
        if (childTreeNodeArray && childTreeNodeArray.length === 0) { // 没有子节点 有记录
          array[getIndex(treeNodeArray, heightTreeNodeArray[n])] = Object.assign({}, heightTreeNodeArray[n], {'checkbox': 'isCheck'});
        } else { // 有子节点 有记录
          let status = getParentCheckBoxStatus(childTreeNodeArray);
          array[getIndex(treeNodeArray, heightTreeNodeArray[n])] = Object.assign({}, heightTreeNodeArray[n], {'checkbox': status});
        }
      } else {
        let childTreeNodeArray = getChildTreeNode(heightTreeNodeArray[n].id, array);
        if (childTreeNodeArray && childTreeNodeArray.length === 0) { // 没有子节点 无记录
          array[getIndex(treeNodeArray, heightTreeNodeArray[n])] = Object.assign({}, heightTreeNodeArray[n], {'checkbox': 'unCheck'});
        } else { // 有子节点 无记录
          let status = getParentCheckBoxStatus(childTreeNodeArray);
          array[getIndex(treeNodeArray, heightTreeNodeArray[n])] = Object.assign({}, heightTreeNodeArray[n], {'checkbox': status});
        }
      }
    }
    heightTreeNodeArray = [];
  }
  return array;
}

// 判断id是否在数组中
function existId(id, idsArray) {
  for (let n = 0; n < idsArray.length; n++) {
    if (id === idsArray[n]) {
      return true;
    }
  }
  return false;
}

// 拷贝数组
function copyArray(treeNodeArray) {
  let array = [];
  for (let n = 0; n < treeNodeArray.length; n++) {
    array.push(treeNodeArray[n]);
  }
  return array;
}

// 返回obj在数组中的位置
function getIndex(treeNodeArray, obj) {
  for (let n = 0; n < treeNodeArray.length; n++) {
    if (treeNodeArray[n].id === obj.id) {
      return n;
    }
  }
}

// 根据level 获取子节点数组
function getTreeNodeWithHeight(height, treeNodeArray) {
  let array = [];
  for (let n = 0; n < treeNodeArray.length; n++) {
    if (treeNodeArray[n].level === height) {
      array.push(treeNodeArray[n]);
    }
  }
  return array;
}

// 根据Pid返回子节点的数组
function getChildTreeNode(pid, treeNodeArray) {
  let array = [];
  for (let n = 0; n < treeNodeArray.length; n++) {
    if (treeNodeArray[n].pid === pid) {
      array.push(treeNodeArray[n]);
    }
  }
  return array;
}

// 根据子节点数组返回父节点CheckBox状态
function getParentCheckBoxStatus(treeNodeArray) {
  let countIsCheck = 0;
  let countUnCheck = 0;
  let countIndeterminate = 0;
  for (let n = 0; n < treeNodeArray.length; n++) {
    if (treeNodeArray[n].checkbox === 'unCheck') {
      countUnCheck++;
    }
    if (treeNodeArray[n].checkbox === 'isCheck') {
      countIsCheck++;
    }
    if (treeNodeArray[n].checkbox === 'indeterminate') {
      countIndeterminate++;
    }
  }
  if (countIndeterminate !== 0) {
    return 'indeterminate';
  }
  if (countUnCheck === 0) {
    return 'isCheck';
  }
  if (countIsCheck === 0) {
    return 'unCheck';
  }
  return 'indeterminate';
}

// id数组中有id删除 没有id新增
function updateIdsArray(id, childIdsArray, idsArray) {
  let array = [];
  let flagExist = false;
  for (let n = 0; n < idsArray.length; n++) {
    if (idsArray[n] === id) {
      flagExist = true;
    } else {
      array.push(idsArray[n]);
    }
  }
  if (!flagExist) { // 不存在 新增
    array.push(id);
    for (let n = 0; n < childIdsArray.length; n++) { // 新增子节点
      array.push(childIdsArray[n]);
    }
  } else { // 存在 删除子节点
    array = deleteIdsFromArray(array, childIdsArray);
  }
  return array;
}

// 从idsArray中删除childIdsArray
function deleteIdsFromArray(idsArray, childIdsArray) {
  let array = [];
  for (let n = 0; n < idsArray.length; n++) {
    if (!existId(idsArray[n], childIdsArray)) {
      array.push(idsArray[n]);
    }
  }
  return array;
}

// 递归 找到Tree中id=id的节点 返回menuChild数组
function getNodeWithParentId(id, treeArray, childArray) {
  for (let n = 0; n < treeArray.length; n++) {
    if (treeArray[n].id === id) {
      childArray = Object.assign(childArray, treeArray[n].menuChild);
      break;
    }
    if (treeArray[n].menuChild && treeArray[n].menuChild !== 0) {
      getNodeWithParentId(id, treeArray[n].menuChild, childArray);
    }
  }
}

// 递归 menuChild数组 找出所有子节点id  放入idsArray
function getChildIds(child, idsArray) {
  if (child && child.length !== 0) {
    for (let n = 0; n < child.length; n++) {
      idsArray.push(child[n].id);
      if (child[n].menuChild !== 0) {
        getChildIds(child[n].menuChild, idsArray);
      }
    }
  }
}

// 从一层数据结构中获取保存的节点id
// function getIdsWithCheckBox(treeNodeArray) {
//   // 处理选中数据
//   let array = [];
//   for (let i = 0, len = treeNodeArray.length; i < len; i++) {
//     if (treeNodeArray[i].checkbox === "isCheck" || treeNodeArray[i].checkbox === "indeterminate") {
//       array.push(treeNodeArray[i].id);
//     }
//   }
//   return array;
// }

// 根据叶子节点CheckBox isCheck状态 从子到父获取Ids
function getIdsWithLeafCheckBox(treeNodeArray) {
  let array = [];
  for (let i = 0, len = treeNodeArray.length; i < len; i++) {
    let id = treeNodeArray[i].id;
    // 是否有子节点
    let flag = false;// 没有子节点
    for (let j = 0, len = treeNodeArray.length; j < len; j++) {
      if (id === treeNodeArray[j].pid) {
        flag = true;// 有子节点
      }
    }
    if (!flag) { // 没有子节点
      if (treeNodeArray[i].checkbox === 'isCheck') {
        array.push(treeNodeArray[i].id);
      }
    }
  }
  getParentIdWithLeaf(array, treeNodeArray, array);
  // 去重返回Ids
  return Array.from(new Set(array));
}

function getParentIdWithLeaf(arrayAllIds, treeNodeArray, arrayChildrenIds) {
  let array = [];
  for (let i = 0, len = arrayChildrenIds.length; i < len; i++) {
    let id = arrayChildrenIds[i];// 取出一个节点id 找父节点
    for (let j = 0, len = treeNodeArray.length; j < len; j++) {
      if (id === treeNodeArray[j].id) { // 找到节点
        let pid = treeNodeArray[j].pid;
        if (pid !== 0) { // 不是根节点
          for (let k = 0, len = treeNodeArray.length; k < len; k++) {
            if (pid === treeNodeArray[k].id) { // 找到父节点
              arrayAllIds.push(treeNodeArray[k].id);
              array.push(treeNodeArray[k].id);
            }
          }
        }
      }
    }// 完成父节点查找
    // 递归
    getParentIdWithLeaf(arrayAllIds, treeNodeArray, array);
  }
}

// 前端对节点delete 递归 返回修改后的treeArray
export function deleteNode(id, root) {
  // console.log(typeof(root.id)+"==="+typeof(id));
  if (root.id + '' === id + '') {
    // undefined 不是关键字，可能会被重新赋值
    return void 0;
  }
  for (let i = 0; i < root.menuChild.length; i++) {
    // arguments.callee 可以降低一次耦合
    let res = deleteNode(id, root.menuChild[i]);
    // console.log("res==="+JSON.stringify(res));
    if (res) {
      root.menuChild[i] = res;
    } else {
      root.menuChild.splice(i, 1)
    }
  }
  return root;
}

export function deleteNodeWithPid(id, pid, root) {
  // console.log(typeof(root.id)+"==="+typeof(id));
  if ((root.id + '' === id + '') && (root.pid + '' === pid + '')) {
    // undefined 不是关键字，可能会被重新赋值
    return void 0;
  }
  for (let i = 0; i < root.menuChild.length; i++) {
    // arguments.callee 可以降低一次耦合
    let res = deleteNodeWithPid(id, pid, root.menuChild[i]);
    // console.log("res==="+JSON.stringify(res));
    if (res) {
      root.menuChild[i] = res;
    } else {
      root.menuChild.splice(i, 1)
    }
  }
  return root;
}
